package com.mdms.init;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.swing.plaf.metal.MetalIconFactory.FolderIcon16;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.mdms.hibernate.HibernateUtils;
import com.mdms.jsf.managedbeans.dictionaries.DictionariesCache;
import com.mdms.logger.Log4j;
import com.mdms.logger.SimplyMDLogger;
import com.mdms.utils.ConfigFolderUtils;
import com.mdms.utils.FacesUtils;

/**
 * Klasa inicjalizująca aplikację podczas uruchamiwania serwera
 * @author Nowak Bartosz
 *
 */
public class Initializer implements ServletContextListener {

	private SimplyMDLogger logger;
	
	public void contextDestroyed(ServletContextEvent arg0) {
	}

	public void contextInitialized(ServletContextEvent arg0) {
		
		Map context =new HashMap();
		String locale = "";
		String layout = "";
		String serwer_num = "";
		try{
		readLocalParametersFromFile(context);
		locale = getParameter(context, "default_locale", "pl");
		layout = getParameter(context, "default_layout", "0");
		serwer_num = getParameter(context, "serwer_No", "");
		}catch(Exception e){
			System.out.println("contextInitialized ERROR readLocalParameterFromFile"+e.getMessage());
		}
		String logConfigPath=(String)context.get("Log4jConfigPath");
		if(logConfigPath==null && logConfigPath.equals("")){
			System.out.println("contextInitialized ERROR no log configurate file path");
			return ;
		}
		try{
			Log4j.init(logConfigPath);
		}catch(Exception e){
			System.out.println("contextInitialized ERROR init Log4j" + e.getMessage());
			return ;
		}
		try{
		logger = new SimplyMDLogger(Initializer.class);
		HibernateUtils.init();
		initWWWUtils(locale,layout,serwer_num);
		initDictCache();
		}catch(Exception e){
			
		}
		
	}
	
	
	/**
	 * Pobranie parametrow z pliku w mdmsConfig
	 * 
	 * @throws SAXException
	 * @throws IOException
	 * @throws ParserConfigurationException
	 */
	private void readLocalParametersFromFile(Map servletContext) throws SAXException, IOException,
			ParserConfigurationException {
		System.out.println("MDms Initializer::readLocalParametersFromFile() - START");
		DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
		DocumentBuilder b = f.newDocumentBuilder();

		InputSource xmlSource = null;
		String configFileName =  "lConfig.xml";
		String configFilePath = ConfigFolderUtils.getWWWConfigLocation()+configFileName;
		try {
			xmlSource = 
				new InputSource(new FileInputStream(configFilePath));
			//zmiana na systemout bo loggera moze tu nie byc jeszcze
			System.out.println("Loaded configuration from default localization: ["+configFilePath+"]");
		} catch (Exception e){
			System.out.println("Not found configuration in default localization: ["+configFilePath+"]");
		}	
		Document xmlDoc = b.parse(xmlSource);

		NodeList params = xmlDoc.getDocumentElement().getElementsByTagName("parameter");
		for (int i = 0; i < params.getLength(); i++) {
			String paramName = "";
			String paramValue = "";
			Node n = params.item(i);
			NodeList childNodes = n.getChildNodes();
			for (int j = 0; j < childNodes.getLength(); j++) {
				Node n2 = childNodes.item(j);
				if (n2.getNodeName().equals("name")) {
					NodeList paramNames = n2.getChildNodes();
					for (int k = 0; k < paramNames.getLength(); k++) {
						Node n3 = paramNames.item(k);
						if (n3.getNodeType() == Node.TEXT_NODE) {
							paramName += n3.getNodeValue();
						}
					}
				}

				if (n2.getNodeName().equals("value")) {
					NodeList paramValues = n2.getChildNodes();
					for (int k = 0; k < paramValues.getLength(); k++) {
						Node n3 = paramValues.item(k);
						if (n3.getNodeType() == Node.TEXT_NODE) {
							paramValue += n3.getNodeValue();
						}
					}
				}
			}

			servletContext.put(paramName, paramValue);
		}
		System.out.println("MDms Initializer::readLocalParametersFromFile() - END");
	}
	
	private void initWWWUtils(String locale,String layout,String serwerNum){
		FacesUtils.setDefLocale(locale);
		FacesUtils.setLayout(layout);
		FacesUtils.setSerwerNo(serwerNum);
	}
	
	private void initDictCache(){
		try{
			logger.debug("Initializer-Init Dict Cache", "START");
			DictionariesCache.initialize();
			//FacesUtils.setManagedBeanValue("dictCache", cache);
			logger.debug("Initializer-Init Dict Cache", "END");
		}catch(Exception e){
			logger.error("Initializer-Init Dict Cache", e);
		}
	}
	
	private String getParameter(Map cont,String propName,String defualtValue){
		if(cont.containsKey(propName)){
			return cont.get(propName).toString();
		}
		return defualtValue;
	}
}
